﻿using MediatR;
using SheepCultivation.API.AddliCation.DepartmentW;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.Reportw
{
    public class ReportSheepTypeHandler : IRequestHandler<ReportSheepTypeCommon, Result>
    {
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;
        public readonly IBaseRepository<Sheepbreed> SheepbreedRepository;

        public ReportSheepTypeHandler(IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Sheepbreed> sheepbreedRepository)
        {
            BasicInformationRepository = basicInformationRepository;
            SheepbreedRepository = sheepbreedRepository;
        }

        public async Task<Result> Handle(ReportSheepTypeCommon request, CancellationToken cancellationToken)
        {
            var res = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var list = from a in BasicInformationRepository.GetAll()
                           join b in SheepbreedRepository.GetAll() on a.SheepbreedId equals b.SheepbreedId
                           where a.SheepStatus==1
                           select new ReportDto
                           {
                               Auricle = a.Auricle,
                               SheepbreedId = a.SheepbreedId,
                               SheepbreedName = b.SheepbreedName,
                               SheepTypeId = a.SheepTypeId
                           };
                if (request.SheepTypeId != -1)
                {
                    list = list.Where(x => x.SheepTypeId == request.SheepTypeId);
                }
                var rea = list.GroupBy(x => x.SheepbreedName).Select(x => new PageDto()
                {
                    name = x.Key,
                    value = x.Count()
                }).ToList() ;

                res.Code = (int)CommonEnumCode.success;
                res.Data = rea;
                res.Msg = "羊只类型分类展示";
            }
            catch (Exception)
            {

                throw;
            }

            return res;
        }
    }
    public class ReportDto
    {
        /// <summary> 
        /// 耳号
        /// </summary>
        public string Auricle { get; set; }
        /// <summary>
        /// 羊只品种Id
        /// </summary>
        public int SheepbreedId { get; set; }
        public string? SheepbreedName { get; set; }
        public int SheepTypeId { get; set; }
    }
    public class PageDto
    {
        public string name { get; set; }
        public int value { get; set; }
    }
}
